/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package yana.tpe.shop.domain.dao.impl;

import java.util.Iterator;
import java.util.List;
import yana.tpe.shop.domain.dao.AbstractDao;
import yana.tpe.shop.domain.domains.AbstractDomain;
import yana.tpe.shop.domain.domains.AccountBook;
import yana.tpe.shop.utils.GUIDUtils;

public abstract class AbstractDaoImpl<T extends AbstractDomain>
        implements AbstractDao<Long, T> {

    protected AccountBookDao accountBookDao;

    public AbstractDaoImpl(AccountBookDao accountBookDao) {
        this.accountBookDao = accountBookDao;
    }

    @Override
    public Long save(T value) {
        value.setId(GUIDUtils.nextId());
        AccountBook instance = getAccountBook();
        List list = instance.getList(getDomainClass());
        list.add(value);
        saveAccountBook(instance);
        return value.getId();
    }

    @Override
    public T get(Long value) {
        return getAccountBook().getEntyty(getDomainClass(), value);
    }

    @Override
    public List<T> list() {
        return getAccountBook().getList(getDomainClass());
    }

    @Override
    public void delete(Long key) {
        AccountBook accountBook = getAccountBook();
        List<T> list = accountBook.getList(getDomainClass());
        for (Iterator<T> it = list.iterator(); it.hasNext();) {
            T t = it.next();
            if (t.getId().equals(key)) {
                it.remove();
                break;
            }
        }
        saveAccountBook(accountBook);
    }

    protected void saveAccountBook(AccountBook instance) {
        accountBookDao.save(instance);
    }

    protected AccountBook getAccountBook() {
        AccountBook get = accountBookDao.get(null);
        if (get == null) {
            throw new NullPointerException("Can't obtain account book.");
        }
        return get;
    }

    protected abstract Class<T> getDomainClass();

}
